package com.znjc.iot.serial;

import com.znjc.iot.domain.IotSerial;
import com.znjc.iot.exception.*;
import com.znjc.iot.listener.MyListener;
import com.znjc.iot.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class SerialPortHandler {
    private static final Integer SLEEP_TIME = 50;

    /**
     * 打开串口
     *
     * @param serials
     * @return
     */
    public static SerialPortUtil openSerialPort(IotSerial serials) {
        try {
            //打开 串口
            SerialPortUtil serialPortUtil = SerialTool.openPort(serials);
            log.info("绑定监听器");
            serialPortUtil.bindListener(new MyListener(), SLEEP_TIME);
            //存储串口信息
            CommonUtil.protUtils.put(serials.getSerialCode(),serialPortUtil);
            CommonUtil.openComs.add(serials.getSerialCode());
            return serialPortUtil;
        } catch (SerialPortParameterFailure e) {
            log.error(e.getMessage());
        } catch (NotASerialPort e) {
            log.error(e.getMessage());
        } catch (NoSuchPort e) {
            log.error(e.getMessage());
        } catch (PortInUse e) {
            log.error(e.getMessage());
        } catch (TooManyListeners e) {
            log.error(e.getMessage());
        }
        return null;
    }
}
